package com.matt.service.impl;

import com.fasterxml.jackson.databind.JavaType;
import com.matt.commons.exception.BusinessException;
import com.matt.controller.po.ContractImportPO;
import com.matt.domain.*;
import com.matt.foundation.annotation.OptsTrace;
import com.matt.foundation.constant.ClienteleConstant;
import com.matt.foundation.constant.ContractConstant;
import com.matt.foundation.constant.ContractProductConstant;
import com.matt.foundation.constant.LeadsConstant;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.query.ClienteleQuery;
import com.matt.foundation.query.PageableQuery;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.ModelUtil;
import com.matt.foundation.utils.StringTOArray;
import com.matt.foundation.vo.*;
import com.matt.repository.*;
import com.matt.repository.base.ClienteleNativeRepository;
import com.matt.service.*;
import com.matt.remoteCall.SsoCallService;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import static com.matt.foundation.constant.OperateConstant.OPERATE_CREATE;


/**
 * ***********************
 * Created by Ron
 * from com.matt
 * on 2018/6/14 0014.
 * ***********************
 */
@Service
public class ClienteleServiceImpl implements ClienteleService {

    @Autowired
    private ClienteleRepository clienteleRepository;
    @Autowired
    private ClienteleNativeRepository clienteleNativeRepository;
    @Autowired
    private SsoCallService ssoCallService;
    @Autowired
    private ContractProductRepository contractProductRepository;
    @Autowired
    private LeadsHistoryRepository leadsHistoryRepository;
    @Autowired
    private LeadsRepository leadsRepository;

    @Autowired
    private TeachCallService teachCallService;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ContractRepository contractRepository;

    @Autowired
    private BudgetTempleteService budgetTempleteService;

    @Autowired
    private ContractService contractService;

    @Override
    public List<Clientele> findByChildName(String areaId, String childName) {
        return clienteleRepository.findByChildNameAndAreaIdAndDeleted(childName, areaId, false);
    }

    @Override
    public Clientele addByLeads(Leads leads){
        //TODO需要根据电话，园区找到一个已经存在的客户
        Clientele clientele = clienteleRepository.findFirstByAreaIdAndChildNameAndMobile(
                leads.getAreaId(), leads.getChildName(), leads.getMobile()
        );
        if (clientele == null) {
            clientele = new Clientele();
            BeanUtils.copyProperties(leads, clientele, "id");
            //ID重置，可能拷贝到了leads的id
            clientele.setId(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32));
        }else{
            BeanUtils.copyProperties(leads, clientele, "id");
        }

        //补充线索的关联关系
        clientele.setLeadsId(leads.getId());

        //一些字段补充
        clientele.setClienteleType("A");
        clientele.setBirthday(leads.getBirthday());

        //延续线索状态
        clientele.setStatus(getClienteleStatus(leads.getStatus()));//客户状态 默认是(未处理)-改为->暂搁置
        clientele.setStatusVal(getClienteleStatusStr(leads.getStatus()));

        clientele.setSignStatus(ClienteleConstant.SignStatus.NON_SIGN.codeOf()); //客户成交状态 默认为未成交
        clientele.setCreated(new Date());
        //clientele.setChildName(clienteleSaveVo.getSysChildName());
        clientele.setChildName(leads.getChildName());
        clientele.setSysChildName(leads.getChildName());

        //清楚掉不需要的数据
        clientele.setLastFollowRecord("手动创建");
        clientele.setLastFollowTime(null);

        //修改线索为已转
        clientele = clienteleRepository.save(clientele);

        return clientele;
    }

    @OptsTrace(code = "10004")
    @Override
    @Transactional
    public ClienteleDetailVo save(String ticket, ClienteleSaveVo clienteleSaveVo, String productRecords, String areaId) {
        Date date = new Date();
        Clientele clientele = null;
        //系统没此客户
        if (StringUtils.isBlank(clienteleSaveVo.getClienteleId()) && StringUtils.isNotBlank(clienteleSaveVo.getLeadsId())) {
            clientele = new Clientele();
            Leads leads = leadsRepository.getOne(clienteleSaveVo.getLeadsId());
//            if (Objects.nonNull(leads) && leads.getStatus() == LeadsConstant.Status.NON_HANDLE.codeOf())
//                throw  new BusinessException(ErrorCode.LEADS_UNABLE_TRANSFER_CLIENTELE,"未处理的线索不能转为客户,请先跟进此线索!");

            BeanUtils.copyProperties(leads, clientele);
            clientele.setId(null);

            //延续线索状态
            clientele.setStatus(getClienteleStatus(leads.getStatus()));//客户状态 默认是(未处理)-改为->暂搁置
            clientele.setStatusVal(getClienteleStatusStr(leads.getStatus()));

            clientele.setSignStatus(ClienteleConstant.SignStatus.NON_SIGN.codeOf()); //客户成交状态 默认为未成交
            clientele.setCreated(new Date());
            //clientele.setChildName(clienteleSaveVo.getSysChildName());
            clientele.setChildName(leads.getChildName());
            //清楚掉不需要的数据
            clientele.setLastFollowRecord("");
            clientele.setLastFollowTime(null);

            //修改线索为已转
            leads.setChangeStatus(LeadsConstant.ChangeStatus.TRANSFER.codeOf());
            leads.setChangeStatusVal(LeadsConstant.ChangeStatus.TRANSFER.valueOf());
            leadsRepository.save(leads);

        }else if(StringUtils.isBlank(clienteleSaveVo.getClienteleId()) && StringUtils.isBlank(clienteleSaveVo.getLeadsId())) {
        	
        	StaffDTO base = ssoCallService.getStaffDTO(ticket);
        	List<ChannelVo> list = budgetTempleteService.findAll(areaId);       	
        	
        	//新增leads
            Leads leads = new Leads();
            Date now = new Date();
            
            leads.setStaffId(base.getId());
            leads.setStaffName(base.getRealName());
            leads.setLastModified(now);
            leads.setLastModifiedId(base.getId());
            leads.setLastModified(now);
            leads.setStatus(LeadsConstant.Status.NON_HANDLE.codeOf());
            leads.setCategory(2);
            leads.setChangeStatus(LeadsConstant.ChangeStatus.TRANSFER.codeOf());
            leads.setChangeStatusVal(LeadsConstant.ChangeStatus.TRANSFER.valueOf());
            leads.setAreaId(areaId);
            
            clientele = new Clientele();
            //线索来源
            for(ChannelVo channelVo : list) {
         	   if(channelVo.getName().equals("其他")) {
         		   leads.setChannelId(channelVo.getId());
         		   leads.setCategory(Integer.valueOf(channelVo.getType()));
         		   leads.setChannel(channelVo.getName());
         		   clientele.setChannelId(channelVo.getId());
         		   clientele.setChannel(channelVo.getName());
         		   clientele.setCategory(Integer.valueOf(channelVo.getType()));
         	   }
            }
            
            leadsRepository.save(leads);
            
            //添加销售动态
            LeadsHistory leadsHistory = new LeadsHistory();
            
            leadsHistory.setType("leads");
            leadsHistory.setContent("在 " + DateUtil.dateToymd(date) + " 创建了本条数据");
            leadsHistory.setOperationType(OPERATE_CREATE);
            leadsHistory.setActualFollowDate(date);
            leadsHistory.setStaffId(base.getId());
            leadsHistory.setStaffName(base.getRealName());
            leadsHistory.setStaffHeadImgUrl(base.getHeadImgUrl());
            leadsHistory.setAreaId(areaId);
            leadsHistory.setLeadsId(leads.getId());
            
            leadsHistoryRepository.save(leadsHistory);
        	
        	
        	
        	clientele.setId(null);
        	clientele.setRelationship("爸爸");

            //延续线索状态
            clientele.setStatus(ClienteleConstant.Status.NON_HANDLE.codeOf());//客户状态 默认是(未处理)-改为->暂搁置
            clientele.setStatusVal(ClienteleConstant.Status.NON_HANDLE.valueOf());

            clientele.setSignStatus(ClienteleConstant.SignStatus.NON_SIGN.codeOf()); //客户成交状态 默认为未成交
            clientele.setCreated(new Date());
            //clientele.setChildName(clienteleSaveVo.getSysChildName());
            clientele.setChildName(clienteleSaveVo.getSysChildName());
                        
            clienteleSaveVo.setLeadsId(leads.getId());
            
        } else {
            //覆盖原有客户
            clientele = clienteleRepository.getOne(clienteleSaveVo.getClienteleId());
        }
                
        
        //建议名
        if (StringUtils.isNotBlank(clienteleSaveVo.getAdviceName())) {
            if (clienteleSaveVo.getAdviceName().equals(clienteleSaveVo.getSysChildName())) {
                clientele.setAdviceName(clienteleSaveVo.getAdviceName());
            } else {
                clientele.setAdviceName(clienteleSaveVo.getOldAdviceName());
            }
        } else {
            clientele.setAdviceName(clienteleSaveVo.getSysChildName());
        }

        if(StringUtils.isNotBlank(clienteleSaveVo.getSysChildName())){
            clientele.setSysChildName(clienteleSaveVo.getSysChildName());
        }else
        if (StringUtils.isBlank(clientele.getSysChildName())) {
            clientele.setSysChildName(clientele.getChildName());
        }

        clientele.setLeadsId(clienteleSaveVo.getLeadsId());
        clientele.setBirthday(clienteleSaveVo.getBirthday());
        clientele.setMobile(clienteleSaveVo.getMobile());
        clientele.setGender(clienteleSaveVo.getGender());
        clientele.setClienteleType(clienteleSaveVo.getClienteleType());
        clientele.setLastModified(date);
        clientele.setName(clienteleSaveVo.getClienteleName());

        //保存客户信息
        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        String staffId = baseInfo.getId();
        String realName = baseInfo.getRealName();
        //保存客户信息
        clientele.setStaffId(staffId);
        clientele.setAreaId(areaId);
        clientele.setStaffName(realName);

        clientele.setLastModifiedId(staffId);

//        Clientele temp = new Clientele();
//        BeanUtils.copyProperties(clientele, temp);
        clientele = clienteleRepository.save(clientele);
        Clientele clienteleVo = clientele;
        //教务系统生成宝宝数据
        teachCallService.addChild(clientele.getId(), clientele.getChildName(), clientele.getNickName(), clientele.getGender(),
                DateUtil.millisToDateTime(clientele.getBirthday().getTime(), "yyyy-MM-dd"), clientele.getAreaId(), clientele.getHomeAddress(),
                clientele.getName(), clientele.getMobile(), clientele.getCompany(), clientele.getRelationship(), clientele.getStaffId());

        //保存客户购买的产品记录
        if (clienteleVo != null && productRecords != null && !"".equals(productRecords)) {
            //反序列号
            JavaType javaType = ModelUtil.objectMapper.getTypeFactory().constructParametricType(ArrayList.class, ContractProduct.class);
            try {
                List<ContractProduct> contractProducts = ModelUtil.objectMapper.readValue(productRecords, javaType);
                for (ContractProduct cp : contractProducts) {
                    cp.setClienteleId(clienteleVo.getId());
                    cp.setType(ContractProductConstant.Type.PLAN.codeOf()); //转为客户时，产品为意向产品
                    cp.setTypeVal(ContractProductConstant.Type.PLAN.valueOf());

                    Product product = productRepository.getOne(cp.getProductId());
                    cp.setProductType(product.getType());
                    cp.setStandardAmount(product.getStandardAmount());
                    cp.setStandardTotalAmount(product.getStandardAmount().multiply(new BigDecimal(cp.getCount())));
                    contractProductRepository.save(cp);

                    //统计预计收入的新建部分
                    // analysisService.createExpectIncome(cp.getClienteleId(), "", cp.getStandardTotalAmount(), CONTRACT_PRODUCT_NEW, product.getType(), clientele.getAreaId(), date);
                }

            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("json 转集合对象异常");
            }
        }

        ClienteleDetailVo clienteleDetailVo = new ClienteleDetailVo();
        BeanUtils.copyProperties(clienteleVo, clienteleDetailVo);
        clienteleDetailVo.setBirthday(clienteleVo.getBirthday() == null ? null : clienteleVo.getBirthday().getTime());
        clienteleDetailVo.setLastFollowTime(clienteleVo.getLastFollowTime() == null ? null : clienteleVo.getLastFollowTime().getTime());
        clienteleDetailVo.setLastModified(clienteleVo.getLastModified() == null ? null : clienteleVo.getLastModified().getTime());
        return clienteleDetailVo;
    }

    private Integer getClienteleStatus(Integer leadsStatus) {
        if (leadsStatus == LeadsConstant.Status.VIEWED.codeOf())
            return ClienteleConstant.Status.ORDERED.codeOf();
        if (leadsStatus == LeadsConstant.Status.ARRIVED.codeOf())
            return ClienteleConstant.Status.ARRIVED.codeOf();
        else
            return ClienteleConstant.Status.NON_HANDLE.codeOf();
    }

    private String getClienteleStatusStr(Integer leadsStatus) {
        if (leadsStatus == LeadsConstant.Status.VIEWED.codeOf())
            return ClienteleConstant.Status.ORDERED.valueOf();
        if (leadsStatus == LeadsConstant.Status.ARRIVED.codeOf())
            return ClienteleConstant.Status.ARRIVED.valueOf();
        else
            return ClienteleConstant.Status.NON_HANDLE.valueOf();
    }

    @OptsTrace(code = "20001")
    //@Override
    public ClienteleDetailVo update(String ticket, Clientele clientele, String productRecords, String channelId) {
        //保存客户信息
        Clientele oldClientele = clienteleRepository.getOne(clientele.getId());

        StaffDTO baseInfo = ssoCallService.getStaffDTO(ticket);
        clientele.setStaffId(oldClientele.getStaffId());
        clientele.setAreaId(oldClientele.getAreaId());
        clientele.setStaffName(oldClientele.getStaffName());
        Date now = new Date();
        clientele.setLastModified(now);

        clientele.setCategory(oldClientele.getCategory());
        clientele.setCreated(oldClientele.getCreated());
        clientele.setAdviceName(oldClientele.getAdviceName());
        clientele.setLeadsId(oldClientele.getLeadsId());
        clientele.setLastFollowTime(oldClientele.getLastFollowTime());
        clientele.setLastFollowRecord(oldClientele.getLastFollowRecord());
        clientele.setLastModifiedId(baseInfo.getId());
        clientele.setStatus(oldClientele.getStatus());
        clientele.setStatusVal(oldClientele.getStatusVal());
        clientele.setSignStatus(oldClientele.getSignStatus());

        BeanUtils.copyProperties(clientele, oldClientele);
//        if(StringUtils.isNotBlank(clientele.getSysChildName())) {
//            oldClientele.setSysChildName(clientele.getSysChildName());
//        }
        oldClientele.setChannelId(channelId);
        Clientele clienteleVo = clienteleRepository.save(oldClientele);
        //保存客户购买的产品记录
        if (clienteleVo != null && productRecords != null && !"".equals(productRecords)) {
            //反序列号
            JavaType javaType = ModelUtil.objectMapper.getTypeFactory().constructParametricType(ArrayList.class, ContractProduct.class);
            try {
                List<ContractProduct> contractProducts = ModelUtil.objectMapper.readValue(productRecords, javaType);
                for (ContractProduct cp : contractProducts) {
                    Product product = productRepository.getOne(cp.getProductId());
                    cp.setProductType(product.getType());
                    cp.setClienteleId(clienteleVo.getId());
                    cp.setType(ContractProductConstant.Type.PLAN.codeOf()); //转为客户时，产品为意向产品
                    cp.setTypeVal(ContractProductConstant.Type.PLAN.valueOf());
                    contractProductRepository.save(cp);
                }

            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("json 转集合对象异常");
            }
        }

        ClienteleDetailVo clienteleDetailVo = new ClienteleDetailVo();
        BeanUtils.copyProperties(clienteleVo, clienteleDetailVo);
        clienteleDetailVo.setBirthday(clienteleVo.getBirthday() == null ? null : clienteleVo.getBirthday().getTime());
        return clienteleDetailVo;
    }

    @Override
    public AdviceNameVo findChilds(String areaId, String childName) {
        AdviceNameVo vo = new AdviceNameVo();
        //当成真是名字查询
        List<Clientele> list = clienteleNativeRepository.findChilds(areaId, childName);
        //当成系统名查询
        Clientele clientele = clienteleRepository.findBySysChildNameAndAreaId(childName, areaId);
        String adviceName = "";
        String oldAdviceName = "";
        if (list.size() == 1) {
            oldAdviceName = list.get(0).getAdviceName();
            adviceName = list.get(0).getAdviceName() + "_A01";
        } else if (list.size() > 1) {
            oldAdviceName = list.get(0).getAdviceName();
            adviceName = StringUtils.substringBefore(list.get(0).getAdviceName(), "A") + "A" + String.format("%02d", Integer.parseInt(StringUtils.substringAfter(list.get(0).getAdviceName(), "A")) + 1);
        }
        vo.setOldAdviceName(oldAdviceName);
        vo.setAdviceName(adviceName);
        vo.setList(list);
        vo.setClienteleId(clientele == null ? "" : clientele.getId());
        return vo;
    }

//    @Override
//    public Page<Clientele> findByCondition(String ticket, ClienteleQuery clienteleQuery, Pageable pageable) {
//        Specification<Clientele> specification = new Specification<Clientele>() {
//            @Override
//            public Predicate toPredicate(Root<Clientele> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
//                List<Predicate> predicates = new ArrayList<>();
//                if (StringUtils.isNotBlank(clienteleQuery.getQueryKey()))
//                    predicates.add(cb.and(cb.like(root.get(clienteleQuery.getQueryKey()), '%' + clienteleQuery.getQueryVal() + '%')));
//                if (StringUtils.isNotBlank(clienteleQuery.getStaffId()))
//                    predicates.add(cb.and(cb.equal(root.get("staffId"), clienteleQuery.getStaffId())));
//                if (clienteleQuery.getStatus() != null)
//                    predicates.add(cb.and(cb.equal(root.get("status"), clienteleQuery.getStatus())));
//
//                query.where(predicates.toArray(new Predicate[predicates.size()]));
//                return query.getRestriction();
//            }
//        };
//        Page<Clientele> clientelePage = clienteleRepository.findAll(specification, pageable);
//        return clientelePage;
//    }

    @Override
    public Page<Clientele> continueClientelesOrFillMoney(ClienteleQuery clienteleQuery, Pageable pageable) {
        List<Clientele> list = clienteleNativeRepository.findByQuery(clienteleQuery);
        Long count = clienteleNativeRepository.count(clienteleQuery);
        return new PageImpl<Clientele>(list,  PageRequest.of(clienteleQuery.getPageNum(), clienteleQuery.getPageSize()), count);
    }

    @Override
    public Page<ClienteleVo> continueClienteles(ClienteleQuery clienteleQuery, Pageable pageable) {

        List<ClienteleVo> list = clienteleNativeRepository.continueClienteles(clienteleQuery);
        //查询对应的（购买产品名称、剩余天数、上次购买数量
        for (ClienteleVo vo : list) {
            List<Object[]> productNameAndRemians = clienteleNativeRepository.findClienteleProducts(vo.getId());
            vo.setPurchasedProduct(productNameAndRemians.get(0)[0] == null ? "" : productNameAndRemians.get(0)[0].toString());
            //剩余数量封装
            String[] productUnits = StringTOArray.stringToArray(productNameAndRemians.get(0)[0] == null ? "" : productNameAndRemians.get(0)[0].toString());
            if (productUnits != null) {
                StringBuffer unit = new StringBuffer("");
                for (String str : productUnits) {
                    if ("全托".equals(str))
                        unit.append("天|");
                    else if ("SAT早教".equals(str))
                        unit.append("课时|");
                }
                if (unit.toString().contains("|"))
                    unit.deleteCharAt(unit.length() - 1);
                vo.setRemainUnit(unit.toString());
            }

            vo.setRemainCount(productNameAndRemians.get(0)[1] == null ? "" : productNameAndRemians.get(0)[1].toString());
            //查询上次购买产品信息
            List<Object[]> lastPurchaseInfo = clienteleNativeRepository.findLastPurchaseInfo(vo.getId());
            vo.setLastPurchasedDate(lastPurchaseInfo.get(0)[0] == null ? "" : lastPurchaseInfo.get(0)[0].toString());
            vo.setLastPurchasedProductName(lastPurchaseInfo.get(0)[1] == null ? "" : lastPurchaseInfo.get(0)[1].toString());
            vo.setLastPurchasedProductCount(lastPurchaseInfo.get(0)[2] == null ? "" : lastPurchaseInfo.get(0)[2].toString());
            vo.setLastPurchasedProductUnit(lastPurchaseInfo.get(0)[3] == null ? "" : lastPurchaseInfo.get(0)[3].toString());
        }
        Long count = clienteleNativeRepository.countContinueClienteles(clienteleQuery);
        return new PageImpl<ClienteleVo>(list,  PageRequest.of(clienteleQuery.getPageNum(), clienteleQuery.getPageSize()), count);
    }

    @OptsTrace(code = "20002")
    @Override
    public Clientele updateClienteStaff(String ticket, String staffId, String staffName, String clienteleId) {
        Clientele clientele = clienteleRepository.getOne(clienteleId);
        clientele.setStaffId(staffId);
        clientele.setStaffName(staffName);
        return clienteleRepository.save(clientele);
    }

    @Override
    public Page<ClienteleListVO> findByName(String areaId, String name, List<String> ids, Pageable query) {
        if (ids != null && ids.size() == 0){
            return null;
        }

        //查找同一个园区的客户
        Page<ClienteleListVO> list = clienteleNativeRepository.findByName(name, areaId, ids, query);
        return list;
    }

    @OptsTrace(code = "20003")
    @Override
    public Clientele deleteById(String ticket, String clienteleId) {
        Clientele clientele = clienteleRepository.getOne(clienteleId);
        clientele.setDeleted(true);
        return clienteleRepository.save(clientele);
    }

    @Override
    public ClienteleVo findById(String clienteleId) {
        ClienteleVo vo = new ClienteleVo();
        Clientele clientele = clienteleRepository.getOne(clienteleId);
        BeanUtils.copyProperties(clientele, vo);
        List<LeadsHistory> leadsHistories = leadsHistoryRepository.findByClientelesIdAndType(clienteleId, "clientele");
        vo.setLeadsHistoryList(leadsHistories);
        return vo;
    }

    @Override
    public ClienteleVo findByLeadsId(String leadsId) {
        ClienteleVo vo = new ClienteleVo();
        List<Clientele> list = clienteleRepository.findByLeadsIdAndDeleted(leadsId, false);
        Clientele clientele = null;
        if(list.size() > 0){
            clientele = list.get(0);
        }

        if(clientele == null){
            return null;
        }

        BeanUtils.copyProperties(clientele, vo);

//        List<LeadsHistory> leadsHistories = leadsHistoryRepository.findByClientelesIdAndType(clienteleId, "clientele");
//        vo.setLeadsHistoryList(leadsHistories);
        return vo;
    }

    @Override
    public ContractStatusVo checkAllContractOver(String clienteleId) {
        List<Contract> contractList = contractRepository.findByClienteleId(clienteleId);
        boolean hasContract = false, nurseryContractEnd = true, earlyContractEnd = true;

        for (Contract contract : contractList) {
            if (contract.getStatus() == ContractConstant.Status.NON_START.codeOf() || contract.getStatus() == ContractConstant.Status.NORMAL.codeOf()) {
                List<ContractProduct> productList = contractProductRepository.findByContractId(contract.getId());
                if (productList.stream().anyMatch(o -> o.getProductType() == 1))
                    nurseryContractEnd = false;
                if (productList.stream().anyMatch(o -> o.getProductType() == 2))
                    earlyContractEnd = false;
            }
            hasContract = true;
        }
        return ContractStatusVo.of(hasContract, nurseryContractEnd, earlyContractEnd);
    }

    @Override
    public Clientele findBySystemChildName(String areaId, String sysChildName, String mobile) {
        //return clienteleRepository.findBySysChildNameAndAreaId(sysChildName,areaId);
        return clienteleRepository.findByChildNameAndAreaIdAndDeletedAndMobile(sysChildName, areaId, false, mobile);
    }

    @Override
    public Clientele findBySystemChildNameAndId(String areaId, String id, String sysChildName) {
        return clienteleNativeRepository.findBySystemChildNameAndId(id, sysChildName, areaId);
    }

    @Override
    public Clientele getById(String clienteleId) {
        return clienteleRepository.getOne(clienteleId);
    }

    public Clientele getById(String areaId, String clienteleId){
        return clienteleRepository.findFirstByAreaIdAndId(areaId, clienteleId);
    }

    @Override
    public Clientele saveOrigin(Clientele clientele) {
        return clienteleRepository.save(clientele);
    }

    /*** 创建10随机 */
    public static String getUuid() {
        return  UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
    @Override
    public void importAdd(StaffDTO staff, List<ContractImportPO> importExcel) {
        for (int i = 0; i < importExcel.size(); i++) {
            Clientele clientele = clienteleRepository.findFirstByAreaIdAndChildNameAndMobile(staff.getAreaId(),importExcel.get(i).getChildName(),importExcel.get(i).getMobile());
            if (Objects.isNull(clientele)) {
                throw new BusinessException(ErrorCode.CLIENTELE_BIRRHDAY_NULL, "客户信息错误");
            }
            Contract contract = new Contract();
            contract.setClienteleId(clientele.getId());
            contract.setIsRenewal(true);
            contract.setName("导入托班合同");
            contract.setBeginDate(importExcel.get(i).getBeginDate());
            contract.setEndDate(importExcel.get(i).getEndDate());
            contract.setSignDate(new Date());
            contract.setPayType(2);
            contract.setPayStatus(1);
            contract.setPayStatusVal("已付清");
            contract.setStatus(1);
            contract.setStatusVal("正常");
            contract.setCode(getUuid());
            contract.setPracticalAmount(BigDecimal.valueOf(importExcel.get(i).getPracticalAmount()));
            contract.setType(1);
            contract.setPayChannel(1);
            Product product = productRepository.findByNameAndAreaIdAndDeletedIsFalse(importExcel.get(i).getProductName(),staff.getAreaId());
            if (Objects.isNull(product)){
                throw new BusinessException(ErrorCode.CLIENTELE_BIRRHDAY_NULL, importExcel.get(i).getProductName() +"产品不存在！");
            }

            List<ContractProduct> contractProducts = new ArrayList<>();
            ContractProduct contractProduct = new ContractProduct();
            contractProduct.setProductId(product.getId());
            //实付金额算出数量
            BigDecimal count1 = BigDecimal.valueOf(importExcel.get(i).getPracticalAmount()).divide(product.getStandardAmount()).setScale(1,BigDecimal.ROUND_HALF_DOWN);
            contractProduct.setCount(count1.doubleValue());
            contractProducts.add(contractProduct);
            Contract vo = contractService.save(staff, contract, ModelUtil.toJson(contractProducts));
            //查询客户合同不为已中止的已付清的合同
            Long count = contractService.findByStatusAndPayStatus(contract.getClienteleId(), ContractConstant.Status.STOP.codeOf(), ContractConstant.PayStatus.NON_PAY.codeOf());
            if (count > 0) {
                clientele.setStatus(ClienteleConstant.Status.ORDER_CASH.codeOf());
                clientele.setStatusVal(ClienteleConstant.Status.ORDER_CASH.valueOf());
            } else {
                clientele.setStatus(ClienteleConstant.Status.SUCCESS.codeOf());
                clientele.setStatusVal(ClienteleConstant.Status.SUCCESS.valueOf());
            }

            //封装客户状态信息
            vo.setClienteleStatus(clientele.getStatus());
            vo.setSignStatus(clientele.getSignStatus());
            saveOrigin(clientele);

            vo.setTotalAmount(BigDecimal.valueOf(importExcel.get(i).getPracticalAmount()));
            vo.setPayType(2);
            //产品数量  开始时间+结束时间
            BigDecimal productCount =  BigDecimal.valueOf(DateUtil.betweenMonths(importExcel.get(i).getEndDate(),importExcel.get(i).getBeginDate())).setScale(2,BigDecimal.ROUND_HALF_DOWN);
//            BigDecimal productCount =  BigDecimal.valueOf(importExcel.get(i).getPracticalAmount()).divide(product.getStandardAmount()).setScale(1,BigDecimal.ROUND_HALF_DOWN);

            if (BigDecimal.valueOf(importExcel.get(i).getPracticalAmount()).compareTo(product.getStandardAmount().multiply(productCount)) >= 0){
                vo.setPayStatus(1);
                vo.setPayStatusVal("已付清");
                vo.setStatus(1);
                vo.setStatusVal("正常");
            }
            contractRepository.save(vo);
        }
    }
}
